#include "UserManagerView.h"
#include "ui_UserManagerForm.h"
#include "GlobalApi/SqliteDb.h"
#include "Auxiliary/View/MessageBoxDialog.h"
#include "AddUserDialog.h"
#include <QDebug>

UserManagerView::UserManagerView(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::UserManagerView)
{
    ui->setupUi(this);
    this->setWindowFlags(Qt::FramelessWindowHint);
    tc = QTextCodec::codecForName("UTF-8");
    InitTable();
}

UserManagerView::~UserManagerView()
{
    delete ui;
}

void UserManagerView::updateTableBtn()
{
    userTableWgt->updateVerControlBtn(model->rowCount());
}

void UserManagerView::InitTable()
{
    userTableWgt = new TableWgt;
    ui->gLayout_userTable->addWidget(userTableWgt);
    userTableWgt->setFixedSize(500,430);
    userTableWgt->sethHeaderHeight(30);
    userTableWgt->setvHeaderWidth(50);
    userTableWgt->showWithVerControlBtn(true);
    userTableWgt->showWithHorControlBtn(false);

    model = new MySqlTableModel(this, SqliteDb::getInstance()->getDB());
    model->setTable("userManager");
    model->select();
    model->setEditStrategy(QSqlTableModel::OnManualSubmit);
    userTableWgt->getTableView()->setModel(model);
    userTableWgt->getTableView()->setColumnHidden(0, true);
    userTableWgt->getTableView()->setColumnHidden(4, true);

    model->setHeaderData(1, Qt::Horizontal, tr("用户名"));
    model->setHeaderData(2, Qt::Horizontal, tr("姓名"));
    model->setHeaderData(3, Qt::Horizontal, tr("用户组"));
    userTableWgt->updateVerControlBtn(model->rowCount());
    updateTableBtn();
}


void UserManagerView::on_Btn_new_clicked()
{
    AddUserDialog *newUserDlg = new AddUserDialog(model, this);
    newUserDlg->show();
}

void UserManagerView::on_Btn_amendpassword_clicked()
{
    int curRow =  userTableWgt->getTableView()->currentIndex().row();

    //将ID为curRow的用户传给修改界面
    ModifiUserPasswd *userPasswd = new ModifiUserPasswd(curRow, model, this);
    connect(userPasswd, SIGNAL(destroyed()) , this, SLOT(updateTableBtn()));
    userPasswd->show();

}

void UserManagerView::on_Btn_delete_clicked()
{
    MessageBoxDialog *messageBox = new MessageBoxDialog(this,\
                             QString(tr("是否确认删除？")));
    int result = messageBox->exec();
    if(result == QDialog::Accepted)
    {
        int curRow =  userTableWgt->getTableView()->currentIndex().row();
        model->removeRow(curRow);
        model->database().transaction();
        if(model->submitAll()){
           model->database().commit();
           updateTableBtn();  // 更新上下翻动按钮状态
        } else {
           model->database().rollback();
        }
    }
}
